import axios from 'axios'
import qs from 'qs'

import store from '@/store'
import router from '@/router'
import config from '@/commons/config'
import tool from '@/commons/libraries/tool'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.timeout = 5000
axios.interceptors.response.use(response => {
  let r = response.data
  if (r.code === 30001) {
    tool.clearLocalStorage()
    store.dispatch('signOut').then(() => {
      router.push({
        path: `/sign/in`
      })
    })
    return r
  }
  return r
}, error => {
  return Promise.reject(error)
})

export default (url, data = null, method = 'POST') => {
  if (method !== 'GET') {
    data = qs.stringify(data)
  }
  // url = process.env.NODE_ENV === 'development' ? `/~${url}` : url
  url = config.getServerUri(url)
  return axios.request({
    url: url,
    method: method,
    data: data
  })
}
